package com.shopping_back.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.apache.commons.io.FilenameUtils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class UploadController {

    @Value("${app.upload.base-dir:uploads}")
    private String uploadDir;

    @Value("${app.upload.avatars:avatars}")
    private String avatarsDir;

    @PostMapping("/avatar")
    public Map<String, String> uploadAvatar(
            @RequestParam("file") MultipartFile file) {

        // 1. 校验文件
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }
        if (!isImage(file)) {
            throw new RuntimeException("只支持图片格式");
        }

        try {
            // 2. 获取项目根目录并创建上传目录
            Path projectRoot = Paths.get("").toAbsolutePath(); // 获取项目根目录
            Path storagePath = projectRoot.resolve(uploadDir).resolve(avatarsDir)
                    .toAbsolutePath()
                    .normalize();

            // 创建目录（如果不存在）
            if (!Files.exists(storagePath)) {
                Files.createDirectories(storagePath);
                System.out.println("创建上传目录: " + storagePath);
            }

            // 3. 生成安全文件名
            String originalFilename = file.getOriginalFilename();
            String ext = originalFilename != null ?
                    FilenameUtils.getExtension(originalFilename) : "jpg";
            String safeName = UUID.randomUUID() + "." + ext;

            // 4. 写入文件
            Path targetPath = storagePath.resolve(safeName);
            file.transferTo(targetPath.toFile());

            // 5. 返回相对URL路径
            String url = "/uploads/" + avatarsDir + "/" + safeName;

            Map<String, String> response = new HashMap<>();
            response.put("url", url);
            response.put("filename", safeName);
            response.put("originalName", originalFilename);

            System.out.println("文件上传成功: " + targetPath);
            System.out.println("访问URL: " + url);

            return response;

        } catch (IOException e) {
            System.err.println("文件上传失败: " + e.getMessage());
            throw new RuntimeException("上传失败: " + e.getMessage(), e);
        }
    }

    // 校验图片类型和大小
    private boolean isImage(MultipartFile file) {
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            return false;
        }

        // 限制文件大小为5MB
        long maxSize = 5 * 1024 * 1024;
        if (file.getSize() > maxSize) {
            throw new RuntimeException("文件大小不能超过5MB");
        }

        return true;
    }
}